'use client';

import { useState, useEffect } from 'react';
import { BSCTokenList } from '@/components/BSCTokenList';
import { CreateBSCTokenForm } from '@/components/CreateBSCTokenForm';
import { BSCTokenDetailModal } from '@/components/BSCTokenDetailModal';
import { PixelHeader } from '@/components/PixelHeader';
import { useBSCWebSocket } from '@/hooks/useBSCWebSocket';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';
import { apiClient } from '@/lib/api';
import type { BSCToken } from '@/types/bsc';

export default function BSCPage() {
  const [activeTab, setActiveTab] = useState<'list' | 'create'>('list');
  const [selectedToken, setSelectedToken] = useState<BSCToken | null>(null);
  const [tokens, setTokens] = useState<BSCToken[]>([]);
  const [stats, setStats] = useState({
    totalTokens: 0,
    totalVolume: '0',
    activeTraders: 0,
    averageRaise: '0'
  });

  // Multi-chain wallet state
  const { connected, chain, address } = useMultiChainWallet();
  const isBSCConnected = connected && chain === 'bsc';

  // WebSocket for real-time updates
  const { isConnected } = useBSCWebSocket({
    onTokenUpdate: (token) => {
      setTokens(prev => prev.map(t => t.id === token.id ? { ...t, ...token } : t));
    },
    onNewToken: (token) => {
      setTokens(prev => [token, ...prev]);
      setStats(prev => ({ ...prev, totalTokens: prev.totalTokens + 1 }));
    },
    onStatsUpdate: (newStats) => {
      setStats(newStats);
    }
  });

  // Load initial data
  useEffect(() => {
    loadTokens();
    loadStats();
  }, []);

  const loadTokens = async () => {
    try {
      console.log('Loading BSC tokens...');
      const data = await apiClient.getBSCTokens();
      console.log('BSC tokens response:', data);
      setTokens(data.tokens || []);
      console.log('Set tokens state:', data.tokens || []);
    } catch (error) {
      console.error('Failed to load BSC tokens:', error);
    }
  };

  const loadStats = async () => {
    try {
      const data = await apiClient.getBSCStats();
      setStats(data);
    } catch (error) {
      console.error('Failed to load BSC stats:', error);
    }
  };

  const handleTokenCreated = (newToken: BSCToken) => {
    setTokens(prev => [newToken, ...prev]);
    setActiveTab('list');
  };

  return (
    <div className="min-h-screen" style={{ background: 'var(--background)' }}>
      <PixelHeader />
      
      {/* 主内容 */}
      <main className="app-container py-8">
        {/* 标题和统计 */}
        <div className="text-center mb-12 w-full">
          <h1 className="text-4xl md:text-6xl font-bold text-white mb-4 font-pixel">
            � BSC Launch Pad
          </h1>
          <p className="text-lg md:text-xl mb-8 font-body" style={{ color: 'var(--foreground)' }}>
            Create and trade tokens on BSC - Support for joint curve pricing
          </p>
          
          {/* 统计数据 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-purple-400 mb-2">{stats.totalTokens}</div>
              <div className="text-gray-400">代币总数</div>
            </div>
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-purple-400 mb-2">{stats.totalVolume} BNB</div>
              <div className="text-gray-400">Total trading volume</div>
            </div>
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-purple-400 mb-2">{stats.activeTraders}</div>
              <div className="text-gray-400">Active Traders</div>
            </div>
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-purple-400 mb-2">{stats.averageRaise} BNB</div>
              <div className="text-gray-400">Average funding</div>
            </div>
          </div>

          {/* WebSocket 连接状态 */}
          <div className="mb-8">
            <div className={`inline-flex items-center px-4 py-2 rounded-lg text-sm font-medium ${
              isConnected 
                ? 'bg-green-600/20 text-green-400 border border-green-600/30' 
                : 'bg-red-600/20 text-red-400 border border-red-600/30'
            }`}>
              <div className={`w-2 h-2 rounded-full mr-2 ${
                isConnected ? 'bg-green-400' : 'bg-red-400'
              }`} />
              {isConnected ? 'connected' : 'disconnected'}
            </div>
          </div>
        </div>

        {/* 功能特色 */}
        <div className="mb-8">
          <div className="flex flex-wrap justify-center items-center gap-6 text-sm text-gray-300">
            <div className="flex items-center space-x-2 pixel-card px-4 py-2">
              <span>📈</span>
              <span>Bonding Curve Pricing</span>
            </div>
            <div className="flex items-center space-x-2 pixel-card px-4 py-2">
              <span>💰</span>
              <span>Automatic liquidity addition</span>
            </div>
            <div className="flex items-center space-x-2 pixel-card px-4 py-2">
              <span>🔄</span>
              <span>Buy and sell at any time</span>
            </div>
            <div className="flex items-center space-x-2 pixel-card px-4 py-2">
              <span>🎯</span>
              <span>Automatically go online if you meet the standards</span>
            </div>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="w-full">
          {activeTab === 'list' ? (
            <BSCTokenList
              tokens={tokens}
              onTokenSelect={setSelectedToken}
            />
          ) : (
            <CreateBSCTokenForm
              onSuccess={handleTokenCreated}
              onClose={() => setActiveTab('list')}
            />
          )}
        </div>
      </main>

      {/* Token Detail Modal */}
      {selectedToken && (
        <BSCTokenDetailModal
          token={selectedToken}
          onClose={() => setSelectedToken(null)}
        />
      )}
    </div>
  );
}